// dom 相关的一些操作

// 判断 dom 对象是否含有 className
export function hasClass(el, className) {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
  return reg.test(el.className);
}

// 给 dom 对象 添加 className
export function addClass(el, className) {
  if (hasClass(el, className)) {
    return;
  }

  let newClass = el.className.split(' ');
  newClass.push(className);
  el.className = newClass.join(' ');
}

export function getData(el, name, val) {
  // 获取 el 的 data-name 属性值，传入val参数时我们就给 el对象 data-name属性赋值
  const prefix = 'data-';
  if (val) {
    return el.setAttribute(prefix + name, val);
  }
  return el.getAttribute(prefix + name);
}

let elementStyle = document.createElement('div').style;

let vendor = (() => {
  let transformNames = {
    webkit: 'webkitTransform',
    Moz: 'MozTransform',
    O: 'OTransform',
    ms: 'msTransform',
    standard: 'transform',
  };

  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      return key;
    }
  }
  return false;
})();

export function prefixStyle(style) {
  // 小驼峰
  let newS1 = style.replace(/(\w*)-(\w*)/g, function($1, $2, $3) {
    return $2 + $3[0].toUpperCase() + $3.slice(1);
  });
  // 大驼峰
  let newS2 = newS1.charAt(0).toUpperCase() + newS1.substr(1);

  let transformNames = {
    webkit: 'webkit' + newS2,
    Moz: 'Moz' + newS2,
    O: 'O' + newS2,
    ms: 'ms' + newS2,
    standard: style,
  };

  let per = '';
  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      per = key;
      break;
    }
  }
  if (per === 'standard' || per === '') {
    return style;
  } else {
    return per + newS2;
  }
}
